/*
 *所有关于tb_project_expensebaseinfo类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*tb_project_expensebaseinfoService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using MYData.Core.BaseProvider;
using MYData.Core.Extensions.AutofacManager;
using MYData.Entity.DomainModels;
using System.Linq;
using MYData.Core.Utilities;
using System.Linq.Expressions;
using MYData.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using MYData.System.IRepositories;
using MYData.Core.EFDbContext;
using OfficeOpenXml.ConditionalFormatting;
using MYData.Entity.DTO.ApiEntity.Input;
using Mapster;
using System.Collections.Generic;
using MYData.Order.Services;
using System.Net;
using System.Threading.Tasks;
using MYData.Entity.DTO.ApiEntity.OutPut;
using System.Reflection;
using System;
using System.Reflection;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;
using MYData.Core.Utilities.Response;
using MYData.Core.ManageUser;
using Newtonsoft.Json;
using NuGet.ContentModel;
using NUnit.Framework;
using System.Collections;

namespace MYData.System.Services
{
    public partial class tb_project_expensebaseinfoService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly Itb_project_expensebaseinfoRepository _repository;//访问数据库
        private readonly VOLContext _context;

        [ActivatorUtilitiesConstructor]
        public tb_project_expensebaseinfoService(
            Itb_project_expensebaseinfoRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
,
            VOLContext context)
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            _context = context;
            //多租户会用到这init代码，其他情况可以不用
            base.Init(dbRepository);
        }

        WebResponseContent webResponse = new WebResponseContent();
        UserInfo userInfo = UserContext.Current.UserInfo;

        /// <summary>
        /// 添加经费报销基础信息表(事务)
        /// </summary>
        /// <returns></returns>
        public WebResponseContent InsertBudgetInfo(BudgetBaseInfoInput_Dto inputDto)
        {

            _context.Database.BeginTransaction();
            try
            {
                //Mapster实体转换
                var model = inputDto.Adapt<tb_project_expensebaseinfo>();

                //流程关系表添加
                tb_project_workflowtable workflowtable = new tb_project_workflowtable();
                var workFlow = _context.Set<Sys_WorkFlow>().Where(s => s.WorkTable == model.subjectId).FirstOrDefault();
                workflowtable.id = Ids.NextIdString();
                workflowtable.workFlowId = workFlow.WorkFlow_Id;
                workflowtable.workName = workFlow.WorkName;
                workflowtable.projectTableKey = model.id;
                workflowtable.projectTable = workFlow.WorkTable;
                workflowtable.workTableName = workFlow.WorkTableName;
                workflowtable.currentOrderId = "1";
                workflowtable.auditStatus = 0;//0是审核中
                workflowtable.createDate = DateTime.Now;
                workflowtable.creator = userInfo.UserName;

                //附件视图转换
                //var fileModel = inputDto.File.Adapt<IEnumerable<FileUploadInput_Dto>>();
                //科目模板信息

                //var fundingmodel = inputDto.fundingitems.Adapt<List<tb_project_budgetemp>>();
                //foreach (var item in fundingmodel)
                //{
                //    item.BudgeId = model.subjectId;
                //}
                //添加基础信息
                _context.Set<tb_project_expensebaseinfo>().Add(model);
                //_context.SaveChanges();
                if (_context.SaveChanges() < 1)
                {
                    _context.Database.RollbackTransaction();
                    return webResponse.Error("添加基础信息失败!");
                }
                _context.Set<tb_project_workflowtable>().Add(workflowtable);
                if (_context.SaveChanges() < 1)
                {
                    _context.Database.RollbackTransaction();
                    return webResponse.Error("添加报销流程关系表失败!");
                }
                //文件上传
                //tb_project_appendixService.Instance.AddFileListTs(fileModel, model.projecId);
                //添加科目报销模板
                //_context.Set<tb_project_budgetemp>().AddRange(fundingmodel);
                _context.SaveChanges();
                //提交事务
                _context.Database.CommitTransaction();

                return webResponse.OK("添加成功!", true);
            }
            catch (global::System.Exception)
            {
                _context.Database.RollbackTransaction();
                return webResponse.Error("添加失败!");
            }
        }

        /// <summary>
        /// 删除项目经费报销信息(逻辑删除)
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> SoftDeleteExpenseInfoAsync(string ExpenseId)
        {
            var model = _context.Set<tb_project_expensebaseinfo>().Find(ExpenseId);
            model.isDelete = 1;
            _repository.Update(model);
            return webResponse.OK("删除成功!", await _repository.SaveChangesAsync());
        }

        /// <summary>
        /// 删除项目经费报销信息(物理删除)
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> DeleteExpenseInfoAsync(string Id)
        {
            var model = _context.Set<tb_project_expensebaseinfo>().Find(Id);
            _repository.Delete(model);
            return webResponse.OK("删除成功!", await _repository.SaveChangesAsync());
        }

        /// <summary>
        /// 修改项目经费报销
        /// </summary>
        /// <returns></returns>
        public async Task<WebResponseContent> UpdateeExpenseInfoAsync(UpdateExpenseInfoDto inputDto)
        {
            //Mappster实体转换
            var Entity = inputDto.Adapt<tb_project_expensebaseinfo>();
            _repository.Update(Entity);
            return webResponse.OK("修改模板成功!", await _repository.SaveChangesAsync());
        }

        /// <summary>
        /// 经费报销显示+查询
        /// wl//2023-4-09//晚上
        /// </summary>
        /// <param name="Search">查询条件</param>
        /// <returns></returns>
        public async Task<WebResponseContent> GetExpensesReimbursement(BillingAllocationSearch_Dto Search)
        {
            var baseinfo = _context.Set<tb_project_baseinfo>().AsQueryable();
            if (!string.IsNullOrEmpty(Search.projectNameOrNum))
            {
                baseinfo = baseinfo.Where(x => x.projectNumber.Contains(Search.projectNameOrNum) || x.projectName.Contains(Search.projectNameOrNum));
            }
            if (Search.projectStarttime != null)
            {
                baseinfo = baseinfo.Where(x => x.projectStarttime >= Search.projectStarttime);
            }
            if (Search.projectEndtime != null)
            {
                baseinfo = baseinfo.Where(x => x.projectStarttime <= Search.projectEndtime);
            }
            if (!string.IsNullOrEmpty(Search.projectPerson))
            {
                baseinfo = baseinfo.Where(x => x.projectPerson.Contains(Search.projectPerson));
            }
            var list = from x in baseinfo.ToList()
                       orderby x.projectStarttime
                       where x.IsDel==0
                       select new BillingAllocationOutput_Dto()
                       {
                           projectId = x.projectId,
                           projectName = x.projectName,
                           projectNumber = x.projectNumber,
                           projectStarttime = x.projectStarttime,
                           projectPerson = x.projectPerson,
                           projectMoney = x.projectMoney,
                           allocationExpenditure = RMoney(x.projectId),
                           ReimbursedExpenses = BMoney(x.projectId),
                           RemainingFunds = RMoney(x.projectId) - BMoney(x.projectId),
                       };
            var info = new
            {
                list = list.ToList().Skip((Search.PageIndex - 1) * Search.PageSize).Take(Search.PageSize),
                NumCount = list.ToList().Count()
            };
            return webResponse.OK("success", info);
        }
        /// <summary>
        /// 入账总经费
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        private int RMoney(string projectId)
        {
            var list= _context.Set<tb_project_billing_allocation>().ToList();
            var allocation= _context.Set<tb_project_billing_allocation>().Where(x => x.projectId == projectId).ToList();
            var rzmoney = 0;
            foreach (var item in allocation)
            {
                rzmoney =((int)(rzmoney + item.allocationExpenditure));
            }
            return rzmoney;
        }
        /// <summary>
        /// 报销经费
        /// </summary>
        /// <returns></returns>
        private int BMoney(string projectId)
        {
            var list = _context.Set<tb_project_expensebaseinfo>().Where(x => x.projecId == projectId).ToList();
            var bmoney = 0;
            foreach (var item in list)
            {
                bmoney =((int)(bmoney+item.SpecialMoney + item.SupportMoney));
            }
            return bmoney;
        }


        /// <summary>
        /// 科目报销信息(根据立项主键查询)
        /// wl//2023-4-10//上午
        /// </summary>
        /// <param name="ProjectId">立项信息主键</param>
        /// <returns></returns>
        public async Task<WebResponseContent> GetAccountReimbursement(string ProjectId)
        {
            var list = from x in _context.Set<tb_project_expensebaseinfo>().ToList()
                       join y in _context.Set<Tb_Project_Fundtemplate_Item>().ToList() on x.subjectId equals y.budgetItemId
                       orderby x.createTime
                       where x.projecId == ProjectId && x.isDelete==0
                       select new ProjectExpenseBaseinfoOutput_Dto()
                       {
                           id = x.id,
                           subjectName = y.budgetitemName,
                           specialMoney = x.SpecialMoney,
                           supportMoney = x.SupportMoney,
                           subjectId = x.subjectId,
                           //dealWithPerson = x.dealWithPerson,
                           ReviewProgress = tb_project_workflowstepService.Instance.GetProgress(x.id, x.subjectId),
                           operate = tb_project_workflowstepService.Instance.GetOperate(x.id, x.subjectId) == null ? "" : JsonConvert.SerializeObject(tb_project_workflowstepService.Instance.GetOperate(x.id, x.subjectId))
                       };
            object res = new { list = list, Count = list.Count() };
            return webResponse.OK("success", res);
        }


        /// <summary>
        /// 报销审批列表显示
        /// </summary>
        /// <returns></returns>
        public WebResponseContent expensebaseinfoList()
        {
            var expensebaseinfo = _context.Set<tb_project_expensebaseinfo>().ToList();
            var fundtemplate_item = _context.Set<Tb_Project_Fundtemplate_Item>().ToList();
            var list = (from x in expensebaseinfo
                        join y in fundtemplate_item on x.subjectId equals y.budgetItemId
                        select new
                        {
                            x.id,
                            y.budgetitemName,
                            x.SpecialMoney,
                            x.SupportMoney,
                            x.subjectId,
                            //x.dealWithPerson,
                            schedule = tb_project_workflowstepService.Instance.GetProgress(x.id, x.subjectId)
                        }).ToList();
            return webResponse.OK("审批列表获取成功", list);
        }

        /// <summary>
        /// 根据报销Id获取报销详细信息
        /// MJZ 2023/04/13 15:40
        /// </summary>
        /// <param name="applyId"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> GetApplyList(string applyId)
        {
            var data = _context.Set<tb_project_expensebaseinfo>().Where(x => x.id.Equals(applyId)).FirstOrDefault();
            return webResponse.OK("报销信息获取成功", data);
        }

    }
}
